package com.ly.base.chapter04.asynchronous;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.time.format.DateTimeFormatter;
import java.util.Comparator;
import java.util.concurrent.CompletableFuture;

public class ABExecutorDemo {
    static final int INDEX = 0;
    static final int TIME = 1;
    static final int ORDER_ID = 2;
    static final int PRODUCT_ID = 3;
    static final int CATEGORY_ID = 4;
    static final int CATEGORY_CODE = 5;
    static final int BRAND = 6;
    static final int PRICE = 7;
    static final int USER_ID = 8;
    static final int USER_AGE = 9;
    static final int USER_SEX = 10;
    static final int USER_REGION = 11;
    static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z");

    static Logger logger = LoggerFactory.getLogger("Test");

    public static void main(String[] args) throws IOException {
        /**
         * 1) 异步执行任务
         * CompletableFuture.runAsync()  在任务不需要返回结果时
         * CompletableFuture.supplyAsync()   在任务需要处理结果时
         */
        CompletableFuture.runAsync(() -> logger.info("开始执行"));
        //为 守护线程 --- 在主线程执行完毕后，也将自动结束,不会再去执行未执行的行动

        //2.1 thenAccept(Consumer)    消费结果
        CompletableFuture.supplyAsync(() ->{
            logger.info("异步操作2.1");
            return "结果2.1";
            }).thenAccept(r -> logger.info(r));

        //2.2 thenAccceptAsync        异步消费结果
        CompletableFuture.supplyAsync(() ->{
            logger.info("异步操作2.2");
            return "结果2.2";
        }).thenAcceptAsync(r -> logger.info(r));

        //2.3 thenApply        转换结果
/*        CompletableFuture.supplyAsync(() ->{
            logger.info("异步操作2.3");
            return "结果2.3";
        }).thenApply(r -> r + "转换后的结果2.3")
          .thenAcceptAsync(r -> logger.info(r));

        System.in.read(); // 不让主线程立刻结束*/

        //2.3 thenApply        转换结果
        CompletableFuture.supplyAsync(() ->{
                    logger.info("异步操作2.4");
                    return "结果2.4";
                }).thenApplyAsync(r -> r + "转换后的结果2.4")
                .thenAcceptAsync(r -> logger.info(r));

        System.in.read(); // 不让主线程立刻结束

        // 2) 处理异步任务的结果
        /**
         * thenApply(Function)     转换结果
         * thenApplyAsync          异步转换结果
         * thenAccept(Consumer)    消费结果
         * thenAccceptAsync        异步消费结果
         */

    }

}
